<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>管理端</title>
    <script src="/js/jquery.js" charset="utf-8"></script>
    <script src="/js/bootstrap.js" charset="utf-8"></script>
    <script src="/js/form_datas.js" charset="utf-8"></script>
    <link rel="stylesheet" href="/css/bootstrap.css">
    <link rel="stylesheet" href="/css/main.css">
  </head>
  <body>
    <div class="page-wrap">
      <div class="page-menu">
        <ul class="nav nav-pills nav-stacked" id="nav">
          <li role="presentation" title="house"><a href="/admin/house" target="_self">房源</a></li>
          <li role="presentation" title="link"><a href="/admin/link" target="_self">友情链接管理</a></li>
          <li role="presentation" title="ad"><a href="/admin/ad" target="_self">广告管理</a></li>
          <li role="presentation" title="broker"><a href="/admin/broker" target="_self">经纪人管理</a></li>
        </ul>
      </div>
      <div class="page-content">
        <div class="navbar navbar-default">
          <form class="navbar-form navbar-left" action="?" method="get">
            <div class="form-group" style="margin-right:20px;">
              <button id="btn_add" type="button" class="btn btn-default glyphicon glyphicon-plus">新建</button>
            </div>
            <div class="form-group" style="margin-right:20px;">
              <button id="btn_remove" type="button" class="btn btn-default glyphicon glyphicon-remove">删除</button>
            </div>
            <div class="form-group">
              <input type="search" class="form-control" name="keyword" value="<%=keyword%>">
              <button type="submit" class="btn btn-default">搜索</button>
            </div>
          </form>
        </div>
        <nav aria-label="Page navigation">
          <ul class="pagination margin-0">
            <li>
              <a href="#" aria-label="Previous">
                <span aria-hidden="true">&laquo;</span>
              </a>
            </li>
            <%
            let start=cur_page-(show_page_count-1)/2;
            let end=(cur_page-0)+(((show_page_count-1)/2)-0);
            if(start<1){
              start=1;
            }
            if(end>all_page_num){
              end=all_page_num;
            }
            for(let page=start;page<=end;page++){%>
              <% if (page == cur_page){%>
                <li><a href="/admin/<%=table%>?page=<%=page%>" >[<%=page%>]</a></li>
              <%}else{%>
                <li><a href="/admin/<%=table%>?page=<%=page%>" ><%=page%></a></li>
              <%}%>
            <%}%>
            <li>
              <a href="#" aria-label="Next">
                <span aria-hidden="true">&raquo;</span>
              </a>
            </li>
          </ul>
        </nav>
        <table class="table" >
          <thead>
            <tr>
              <% for(let name in jsonShowName){ %>
                <%if(name=='ID'){%>
                  <th >
                    <label id="checkboxBtn">
                      <input type="checkbox" id="checkboxAll">
                      <%=jsonShowName[name]%>
                    </label>
                  </th>
                <% }else{ %>
                  <th><%=jsonShowName[name]%></th>
                <% } %>
              <% } %>
              <th>编辑</th>
            </tr>
          </thead>
          <tbody>
            <% data.forEach(json=>{%>
            <tr>
              <% for(let name in jsonShowName){ %>
                <%if(name=='ID'){%>
                  <th >
                    <label id="checkboxBtn">
                      <input type="checkbox" id="checkboxAll" name="ID_check" value="<%=json[name]%>">
                      <%=json[name]%>
                    </label>
                  </th>
                <% }else{ %>
                  <th><%=json[name]%></th>
                <% } %>
              <% } %>
              <td>
                <a href="javascript:;" onclick="mod_data('<%=json.ID%>')">编辑</a>
                <a href="/admin/<%=table%>/delete?id=<%=json.ID%>" onclick="return confirm('确定删除吗？')">删除</a>
              </td>
            </tr>
            <%})%>
          </tbody>
        </table>
      </div>
    </div>

    <div id="shadow" class="shadow"></div>
    <div id="dialog" class="panel panel-default add_modify_dialog">
      <div class="panel-heading">
        <h3 class="panel-title">
          添加/修改
          <a href="#" id="btn_close" class="pull-right glyphicon glyphicon-remove"></a>
        </h3>
      </div>
      <div class="panel-body" style="overflow:auto; height:460px;">
        <form id="data_form" class="form-horizontal" method="post" enctype="multipart/form-data">
          <input type="hidden" id="is_mod" name="is_mod" value="false">
          <input type="hidden" name="old_id" id="old_id" value="">
          <div id="form_contrainer">

          </div>
          <div class="form-group">
            <div class="col-sm-10 col-sm-offset-2">
              <button type="submit" class="btn btn-primary">提交</button>
              <button id="btn_cancel" type="button" class="btn btn-danger">取消</button>
            </div>
          </div>
        </form>
      </div>
    </div>

    <script>
      const $=document.querySelectorAll.bind(document)
      let oShadow=$('#shadow')[0];
      let oDialog=$('#dialog')[0];
      $('#btn_add')[0].onclick=function(){
        oShadow.style.display='block';
        oDialog.style.display='block';
        $('#is_mod')[0].value='false';
        createForm();
      }
      $('#btn_cancel')[0].onclick=function(){
        oShadow.style.display='none';
        oDialog.style.display='none';
      }
      $('#btn_close')[0].onclick=function(){
        oShadow.style.display='none';
        oDialog.style.display='none';
      }
      const form_inputs=form_datas['<%=table%>'];

      // 动态生成表单
      let oFormContainer=$('#form_contrainer')[0];

      function createForm(old_data={}){
       
        oFormContainer.innerHTML='';
        form_inputs.forEach((item,index)=>{
          let oDiv=document.createElement('div');
          oDiv.className='form-group';
          oDiv.innerHTML=
          `
          <label for="id${index}" class="col-sm-2 control-label">${item.title}</label>
          <div class="col-sm-10">
            <input type="${item.type}" ${item.multiple?'multiple':''} class="form-control" name="${item.name}" id="id${index}" placeholder="请输入${item.title}..." value="${old_data[item.name]||''}">
          </div>
          `
          oFormContainer.appendChild(oDiv);
          // 单独处理时间
          if(item.type=='date'){
            function toDOU(n){
              return n>=10?(''+n):('0'+n);
            }
            
            if(old_data[item.name]&&old_data[item.name]!='0'){
              
              let oDate=new Date(old_data[item.name]*1000);
              document.getElementById(`id${index}`).value=oDate.getFullYear()+'-'+toDOU((oDate.getMonth()+1))+'-'+toDOU(oDate.getDate());
            }
          }
        })
      }
      
      // 提交之前
      let oForm=$('#data_form')[0];
      oForm.onsubmit=function(){
        form_inputs.forEach(item=>{
          if(item.type=='date'){
            let oInput=document.getElementsByName(item.name)[0];

            let time=Math.floor(new Date(oInput.value).getTime()/1000);

            let oNewInput=document.createElement('input');
            oNewInput.type='hidden';
            oNewInput.name=item.name;
            oInput.name='';
            oNewInput.value=time;
            oFormContainer.appendChild(oNewInput);
          }
        });
      };
      
      //删除
      let oBtnDelBatch=$('#btn_remove')[0];
      let aCheck=Array.from(document.getElementsByName('ID_check'));
      oBtnDelBatch.onclick=function(){
        let arr=[];
        aCheck.forEach(item=>{
          if(item.checked){
            arr.push(item.value)
          }
        })
        if(arr.length==0){
          alert('请选择要删除的项')
        }else{
          let url=`/admin/house/delete?id=${encodeURIComponent(arr.join(','))}`;
          if(confirm(`您确定要删除${arr.length}项吗？`)){
            location.href=url;
          }
        }
      }
      //全选
      let oBtnCheckedAll=$('#checkboxAll')[0];
      $('#checkboxBtn')[0].onclick=function(){
        if(oBtnCheckedAll.checked){
          for(let i=0;i<aCheck.length;i++){
            aCheck[i].checked=true;
          }
        }else{
          for(let i=0;i<aCheck.length;i++){
            aCheck[i].checked=false;
          }
        }
      }
      // 编辑按钮

      function mod_data(id){
        jQuery.ajax({
          type: "get",
          url: "/admin/<%=table%>/get_data",
          data: {id},
          success(res) {
            oShadow.style.display='block';
            oDialog.style.display='block';
            $('#is_mod')[0].value='true';
            $('#old_id')[0].value=res.ID;
            createForm(res);
          },
          error(err){
            alert('数据没找到，请刷新重试');
          }
        });
      }

      // 左侧导航栏切换
      let oNav=$('#nav')[0];
      Array.from(oNav.children).forEach(li=>{
        li.className=li.title=='<%=table%>'?'active':'';
      })
      
    </script>
  </body>
</html>
